var bt = baidu.template;
var Page = {
    header:$('#nav'),
    navList: $('#nav a'),
    contentList: $('.category-wrapper'),
    arrowList : $('.arrow-icon'),
    contentMask : $('.category-mask'),
    productList : $('#product-list'),
    emptyList : $('#empty-list'),
    url : '/tp/products/',
    page : 1,
    initHeader :function(){
        //顶部菜单点击
        var currentContent = {},
            _self = this;

        _self.navList.on('click',function(){
            _self.navList.filter('.cur').removeClass('cur');
            $(this).addClass('cur');

            var type = $(this).data('type'),
                lastContent = _self.contentList.filter('.show'),
                lastArrow = _self.arrowList.filter('.show');

            currentContent = _self.contentList.filter('[data-type='+type+']');
            var currentArrow = _self.arrowList.filter('[data-type='+type+']');
            lastContent.removeClass('show');
            currentContent.addClass('show');
            lastArrow.removeClass('show');
            currentArrow.addClass('show');
            _self.contentMask.addClass('show');

            $('body').on('touchmove',offMove);
        });
        _self.contentMask.on('click',function(){
            _self.navList.filter('.cur').removeClass('cur');
            _self.contentList.filter('.show').removeClass('show');
            _self.arrowList.filter('.show').removeClass('show');
            _self.contentMask.removeClass('show');

             $('body').off('touchmove',offMove);
        })
        var myScroll = {
            category :  new iScroll('category-wrapper', {
                            hScroll : false
                        }),
            dest :  new iScroll('dest-wrapper', {
                            hScroll : false
                        }),
            start :  new iScroll('start-wrapper', {
                            hScroll : false
                        }),
            depart :  new iScroll('depart-wrapper', {
                            hScroll : false
                        })
        } 
        _self.navList.on('touchstart',function(){
            if(!$(this).hasClass('cur')){
                var type = $(this).data('type'),
                    scroll = myScroll[type];
                scroll && scroll.refresh();
            }
        });
        function offMove(e){
            if(e.target == currentContent.get(0) || $.contains(currentContent.get(0),e.target)){
                return;
            }else{
                e.preventDefault();
            }
        }
    },
    setCountDown: function ( time, id ) {
        var _self = this;
        var _obj = {
            product: id,
            sec: document.getElementById("sec-"+id),
            mini: document.getElementById("mini-"+id),
            hour: document.getElementById("hour-"+id),
            day: document.getElementById("day-"+id)
        };
        _self.fnTimeCountDown(time, _obj);
    },
    handleDOM: function() {
        var _self = this;
        var _li = $('#product-list').find('li');
        $.each(_li, function(i, val) {
            if ( $(this).data('time') ) {
                var _id = $(this).data('id'),
                    _time = $(this).data('time') * 1000;
                _self.setCountDown( _time, _id );
                $(this).find('.countdown p').removeClass('hide');
            }else{
                $(this).find('.countdown').hide();
            }
        });
    },
    fnTimeCountDown: function(d, o) {
        var f = {
            zero: function(n) {
                var n = parseInt(n, 10);
                if (n > 0) {
                    if (n <= 9) {
                        n = "0" + n;
                    }
                    return String(n);
                } else {
                    return "00";
                }
            },
            dv: function() {
                d = d || Date.UTC(2050, 0, 1);
                var future = new Date(d),
                    now = new Date();
                //现在将来秒差值
                var dur = Math.round((future.getTime() - now.getTime()) / 1000) + future.getTimezoneOffset() * 60,
                    pms = {
                        sec: "00",
                        mini: "00",
                        hour: "00",
                        day: "00",
                        month: "00",
                        year: "0"
                    };
                if (dur > 0) {
                    pms.sec = f.zero(dur % 60);
                    pms.mini = Math.floor((dur / 60)) > 0 ? f.zero(Math.floor((dur / 60)) % 60) : "00";
                    pms.hour = Math.floor((dur / 3600)) > 0 ? f.zero(Math.floor((dur / 3600)) % 24) : "00";
                    pms.day = Math.floor((dur / 86400)) > 0 ? f.zero(Math.floor((dur / 86400))) : "00";
                }else if(dur < 0 && $(o.sec).parents('.countdown').hasClass('countdown-seckill') ){
                    $(o.sec).parents('p').html('抢购进行中');
                }
                return pms;
            },
            ui: function() {
                if (o.sec) {
                    o.sec.innerHTML = f.dv().sec;
                }
                if (o.mini) {
                    o.mini.innerHTML = f.dv().mini;
                }
                if (o.hour) {
                    o.hour.innerHTML = f.dv().hour;
                }
                if (o.day) {
                    o.day.innerHTML = f.dv().day;
                }
                setTimeout(f.ui, 1000);
            }
        };
        f.ui();
    },
    topSlider : function () {
        $('#slider').slick({
            accessibility: false,
            centerMode: true,
            centerPadding: '204px',
            slidesToShow: 1,
            arrows: false,
            autoplay: true,
            autoplaySpeed: 3000,
        });
        var banner = $('#slider');
        if ( banner.length ) {
            banner.find('.banner').on('click', function(e) {
                var url = $(this).attr('data-url');
                btAppSchema.jumpToWebView(url);
            });
        }
    },
    initItemSelector : function(){
        var _self = this;
        _self.contentList.find('li').on('click',function(){
            var parent = $(this).parent(),
                type = parent.parent().data('type'),
                currentNav = _self.navList.filter('[data-type='+type+']'),
                text = $(this).html();
            if(text != '全部'){
                currentNav.html(text + (type=='depart'?'出发':''));
            }else{
                currentNav.html(currentNav.data('title'));
            }
            //百度统计，筛选tab点击量
            _hmt.push(['_trackEvent', '旅游产品列表tab-' + currentNav.data('title'), 'click', '旅游产品列表tab-' + currentNav.data('title') + '-' + $.trim(text)]);
            currentNav.data('value',$(this).data('value'));
            _self.contentMask.trigger('click');
            parent.find('.cur').removeClass('cur');
            $(this).addClass('cur');
            _self.getProduct(true);
        })
    },
    triggerBanner: function () {
        var banner = $('#slider'),
            category = $('#category').data('value'),
            dest = $('#dest').data('value'),
            start = $('#start').data('value'),
            depart = $('#depart').data('value');
        if ( category == '' && dest == '' && start == '' && depart == '' ) {
            banner.show();
        } else{
            banner.hide();
        };
    },
    getProduct : function(reload){
        var _self = this;
        if(reload){
            _self.emptyList.hide();
            $('#loading-more').show();
            _self.page = 1;
            _self.triggerBanner();
        }
        $.get(_self.url, {
            category : $('#category').data('value'),
            dest : $('#dest').data('value'),
            start : $('#start').data('value'),
            depart : $('#depart').data('value'),
            page : _self.page
        },function(data) {

            //  第一次加载就没数据
            if(reload && data.products.length == 0){
                _self.productList.hide().empty();
                $('#loading-more').hide();
                _self.emptyList.fadeIn();
                $(document).off('scroll', _self.loadMoreProducts());
            }else{

                if(data.has_more){
                    _self.page = data.next_page;
                    $(document).on('scroll', _self.loadMoreProducts());
                    $('#loading-more').show();
                }else{
                    $(document).off('scroll', _self.loadMoreProducts());
                    $('#loading-more').hide();
                }
                _self.emptyList.hide();
                var content = bt('product_template', {list: data.products});
                if(reload){
                    _self.productList.hide().empty().append(content).fadeIn();
                }else{
                    _self.productList.append(content);
                }
                _self.handleDOM();
                
            }
            
        });
    },
    loadMoreProducts : function(){
        var _self = this;
        this.loadHandel = this.loadHandel || function(e){
            var reachBottom = document.body.scrollTop + window.innerHeight >= $(document).height() - 200;
            if ( reachBottom ) {
                $(document).off('scroll',_self.loadMoreProducts());
                _self.getProduct(false);
            }
            
        };
        return this.loadHandel;
    },
    initEmptyList : function(){
        this.emptyList.css('top',($(window).height()-this.header.height()-200)/2);
    },
    initTripproduct : function(){
        this.productList.on('click','li',function(e){
            e.preventDefault();
            var _url = $(this).data('url');
            btAppSchema.jumpToWebView(_url);
        })
    },
    initSearchParam :function(){

        var _self = this;
        $.each(['category','dest','start','depart'],function(index,item){
            var value = getQuery(item);
            if(value){
                value = decodeURIComponent(value);
                var selectItem = _self.contentList.filter('[data-type="'+item+'"]').find('li[data-value="'+value+'"]');
                if(selectItem.length > 0){
                    $('#'+item).data('value',value).html(selectItem.html() + (item=='depart'?'出发':''));
                    selectItem.addClass('cur');
                }
            }
        });
        function getQuery(query){
            var pos = 0,params,match,kvs;
            if((pos = location.search.indexOf("?")) === -1)
                return null;
            else{
                params = location.search.substr(pos+1).split("&");
                for(var i=0;i<params.length;i++){
                    kvs = params[i].split("=");
                    if(kvs[0] == query){
                        return kvs[1] || "";
                    }
                }
            }
            return null;
        }
    }
}
$(function(){
    Page.topSlider();
    Page.initHeader();
    Page.initItemSelector();
    Page.initEmptyList();
    Page.initTripproduct();
    Page.initSearchParam();
    Page.getProduct(true);
});